﻿using System;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;

namespace InstaGM
{
    partial class Form1 : Form
    {
        //Add some Event Handles for Controls
        public void AddControlEvent()
        {
            tabControl1.Selected += load_on_tab;
            summon_grid.Click += dataGridView1_Click;
            item_grid_search.Click += clear_search_text;
            item_grid_search.KeyPress += new KeyPressEventHandler(this.item_async);
            item_grid_search.TextChanged += reset_list;
            state_grid.DoubleClick += state_grid_insert;
            state_grid_search.Click += clear_search_text;
            state_grid_search.KeyPress += new KeyPressEventHandler(this.state_async);
            state_grid_search.TextChanged += reset_list;
            richTextBox1.TextChanged += scroll_log;

        }

        //Clear searchbox text on click
        public void clear_search_text(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 2)
            {
                item_grid_search.Text = "";
                item_grid.Rows[0].Selected = true;
                item_grid.FirstDisplayedScrollingRowIndex = 0;
            }
            if (tabControl1.SelectedIndex == 3)
            {
                state_grid_search.Text = "";
                state_grid.Rows[0].Selected = true;
                state_grid.FirstDisplayedScrollingRowIndex = 0;
            }
        }

        //Reset the selected row on the grid
        public void reset_list(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 2)
            {
                if (item_grid_search.Text.Length == 0)
                {
                    item_grid.Rows[0].Selected = true;
                    item_grid.FirstDisplayedScrollingRowIndex = 0;
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                if (state_grid_search.Text.Length == 0)
                {
                    state_grid.Rows[0].Selected = true;
                    state_grid.FirstDisplayedScrollingRowIndex = 0;
                }
            }
        }

        //Execute raw command upon enter pressed
        public void exec_raw_send(object sender, KeyEventArgs k)
        {
            if (k.KeyCode == Keys.Enter)
            {
                raw_cmd_issued = true;
                sendcommand(command.Text);
            }
        }

        //Run Async Search of Item Grid
        public void item_async(object sender, KeyPressEventArgs k)
        {
            if (tabControl1.SelectedIndex == 2)
            {
                int result = item_grid.Rows.GetFirstRow(DataGridViewElementStates.Selected) + 1;

                while (result < item_grid.Rows.Count)
                {
                    if (k.KeyChar == (char)Keys.Back)
                    {
                        if (item_grid_search.Text.Length == 0)
                        {
                            item_grid.Rows[0].Selected = true;
                            item_grid.FirstDisplayedScrollingRowIndex = 0;
                            break;
                        }
                        break;
                    }

                    try
                    {
                        if (!item_grid.Rows[result].Cells[1].Value.ToString().ToLower().Contains(item_grid_search.Text.ToLower()))
                        {
                            result++;
                        }
                        else
                        {
                            item_grid.FirstDisplayedScrollingRowIndex = result;
                            item_grid.Rows[result].Selected = true;
                            break;
                        }
                    }
                    catch
                    {
                        break;
                    }
                }
            }
        }

        //Run Async Search of State Grid
        public void state_async(object sender, KeyPressEventArgs k)
        {
            if (tabControl1.SelectedIndex == 3)
            {
                int result = state_grid.Rows.GetFirstRow(DataGridViewElementStates.Selected) + 1;

                while (result < state_grid.Rows.Count)
                {
                    if (k.KeyChar == (char)Keys.Back)
                    {
                        if (state_grid_search.Text.Length == 0)
                        {
                            state_grid.Rows[0].Selected = true;
                            state_grid.FirstDisplayedScrollingRowIndex = 0;
                            break;
                        }
                        break;
                    }

                    try
                    {
                        if (!state_grid.Rows[result].Cells[1].Value.ToString().ToLower().Contains(state_grid_search.Text.ToLower()))
                        {
                            result++;
                        }
                        else
                        {
                            state_grid.FirstDisplayedScrollingRowIndex = result;
                            state_grid.Rows[result].Selected = true;
                            break;
                        }
                    }
                    catch
                    {
                        break;
                    }
                }
            }
        }

        //Load Character List
        public void load_characters()
        {
            if (!Directory.Exists(tmp))
            {
                Directory.CreateDirectory(tmp);
            }
            string str = Path.Combine(this.tmp, "character_list.txt");
            if (!File.Exists(str))
            {
                using (TextWriter textWriter = new StreamWriter(File.Create(str)))
                {
                    textWriter.Write("TealSky");
                }
            }
            using (TextReader textReader = new StreamReader(str))
            {
                int i = 1;

                while (textReader.Peek() != -1)
                {
                    chars_read = i++;
                    char_list.Items.Add(textReader.ReadLine());
                }
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(""+chars_read+" Characters Read from local character_list.txt\n>\n"); }));
            }
        }

        //Load Summon List
        public void load_summon()
        {
            string str = Path.Combine(this.tmp, "summon_list.txt");
            string str1 = str;

            using (TextReader textReader = new StreamReader(File.OpenRead(str1)))
            {
                int i = 1;

                while (textReader.Peek() != -1)
                {
                    summons_read = i++;
                    char[] chrArray = new char[] { '\t' };
                    summon_grid.Rows.Add(textReader.ReadLine().Split(chrArray));
                }
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\n\n" + summons_read + " Summons Read from local summon_list.txt\n>\n"); }));
            }
        }

        //Load Item List
        public void load_item(object sender, DoWorkEventArgs e)
        {
            string str = Path.Combine(this.tmp, "item_list.txt");
            string str1 = str;
            using (TextReader textReader = new StreamReader(File.OpenRead(str1)))
            {
                int i = 1;

                while (textReader.Peek() != -1)
                {
                    items_read = i++;
                    this.Invoke(new MethodInvoker(delegate { iloaded.Text = "" + items_read + " Items Loaded"; }));
                    char[] chrArray = new char[] { '\t' };
                    this.Invoke(new MethodInvoker(delegate { item_grid.Rows.Add(textReader.ReadLine().Split(chrArray)); }));
                }
            }
        }

        //Load State List
        public void load_state(object sender, DoWorkEventArgs e)
        {
            string str = Path.Combine(this.tmp, "state_list.txt");
            string str1 = str;
            using (TextReader textReader = new StreamReader(File.OpenRead(str1)))
            {
                int i = 1;
                string line = textReader.ReadLine(); 

                while (textReader.Peek() != -1)
                {
                    string state_id = line.Split('\t')[0];
                    string state_name = line.Split('\t')[1];
                    string state_lv = line.Split('\t')[2];
                    string state_desc = line.Split('\t')[3];

                    states_read = i++;
                    this.Invoke(new MethodInvoker(delegate { sLoaded.Text = "" + states_read + " States Loaded"; }));
                    char[] chrArray = new char[] { '\t' };
                    this.Invoke(new MethodInvoker(delegate { state_grid.Rows.Add(textReader.ReadLine().Split(chrArray)); }));
                }
            }
        }

        //Scroll Log on new input
        public void scroll_log(object sender, EventArgs e)
        {
            this.Invoke(new MethodInvoker(delegate { richTextBox1.ScrollToCaret(); }));
        }

        //Connect to Telnet
        public void connect(string passwd)
        {
            //We should update the UI with some information so the program doesn't appear to be just sitting
            this.Invoke(new MethodInvoker(delegate { status.Text = "Authenticating"; }));
            this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\nAttempting to Establish Telnet Connection..\nRequest Sent!\nWaiting for a response...\n\n"); }));

            //While the TCP Client is connected we need to do some information exchange
            while (tcpc.Connected)
            {
                Int32 bytes = ns.Read(output, 0, output.Length);
                responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(responseoutput); }));
                objToMatch = new Regex("Password");

                if (objToMatch.IsMatch(responseoutput))
                {
                    cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
                    // Check to see if this NetworkStream is writable. 
                    if (ns.CanWrite)
                    {
                        //
                        pass_sent = true;
                        ns.BeginWrite(cmd, 0, cmd.Length,
                                                                     new AsyncCallback(sys), ns);
                    }
                }
            }
        }

        //Send Summon To Clip-Board
        public void sendtoclip(string clip_cmd)
        {
            if (status.Text != "Working")
            {
                this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
            }
            this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\nCommand Sent to Clip Board\n" + clip_cmd + "\n" + ">"); }));
            if (status.Text == "Working")
            {
                this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
            }
            Clipboard.SetText(clip_cmd);
        }

        //Send Telnet Command
        public void sendcommand(string command)
        {
            if (status.Text == "Idle")
            {
                cmd = System.Text.Encoding.ASCII.GetBytes(command + "\r");
                if (ns.CanWrite)
                {
                    this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                    cmd_issued = true;
                    ns.BeginWrite(cmd, 0, cmd.Length,
                                                                    new AsyncCallback(sys), ns);
                }
            }
        }

        //System Response 
        public void sys(IAsyncResult result)
        {
            //Define Server Responses
            Int32 bytes = ns.Read(output, 0, output.Length);
            responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
            
            //If the command was issued from an automated source
            if (cmd_issued == true)
            {
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(cmd_txt + "\n"); }));  
                cmd_issued = false;
            }
            //If the command was issued via Raw Command
            if (raw_cmd_issued == true)
            {
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(command.Text + "\n"); }));
                raw_cmd_issued = false;
                this.Invoke(new MethodInvoker(delegate { command.Text = ""; }));
            }
            //If the command is the password being sent
            if (pass_sent == true)
            {
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\nSending Password: " + pass_val + "\n"); }));    
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\n" + responseoutput + "\n"); }));
                pass_sent = false; 
            }
            else //unhandled communication
            {
                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText(responseoutput+ "_unhandled_" + "\n"); }));   
            }
            //Since we are complete with our communications are complete for the time being 
            //We should tell the ui that we aren't doing anything
            this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
        }

        //Check Raw Command Before Transmission
        private void button1_Click_1(object sender, EventArgs e)
        {
            //Lets make sure the command isn't empty
            if (!string.IsNullOrEmpty(command.Text))
            {
                //For easy referemce lets give the command it's own handle
                string reference = command.Text;

                //If the reference begins with our disallowed commands we should stop it from being transmitted
                if (reference.StartsWith("list") || reference.StartsWith("#list") || reference.StartsWith("#get_env") || reference.StartsWith("#set_env") || reference.StartsWith("#suicide"))
                {
                    //Display Informational Message
                    MessageBox.Show("The following commands are NOT allowed for use in InstaGM:\n\n-list\n-#list\n-#get_env\n-#set_env\n-#suicide\n\nThe above commands are disallowed for possible security circumstances.");
                }
                else
                {
                    //If our reference starts with # we should check it further
                    if (reference.StartsWith("#"))
                    {
                        //If our reference contains some bad escape/un-needed syntax
                        if (reference.Contains(".") || reference.Contains("[") || reference.Contains("]") || reference.Contains("\\") || reference.Contains("/"))
                        {
                            //Display Informational Message
                            MessageBox.Show("The use of non-relevant escaping/syntax is not allowed!");
                        }
                        else
                        {
                            //We should make sure our raw_cmd_issue trigger is set
                            raw_cmd_issued = true;
                            //Our reference has been cleared of garbage (we think)
                            //So lets pass him on
                            sendcommand(reference);
                        }
                    }
                    else
                    {
                        //Our reference did not begin with # so it won't be accepted
                        MessageBox.Show("All commands should start with #");
                    }
                }
            }
            else
            {
                //Our reference was blank
                MessageBox.Show("You haven't entered a command yet");
            }
        }

        //Return Job ID
        public static int get_job_id(string Job_name)
        {
            if (!string.IsNullOrEmpty(Job_name))
            {
                string str = Job_name;

                switch (str)
                {
                    case "Rogue":
                        {
                            return 100;
                        }
                    case "Fighter":
                        {
                            return 101;
                        }
                    case "Spell Singer":
                        {
                            return 102;
                        }
                    case "Champion":
                        {
                            return 110;
                        }
                    case "Archer":
                        {
                            return 111;
                        }
                    case "Druid":
                        {
                            return 112;
                        }
                    case "Battle Kahuna":
                        {
                            return 113;
                        }
                    case "Evoker":
                        {
                            return 114;
                        }
                    case "Berserker":
                        {
                            return 120;
                        }
                    case "Marksman":
                        {
                            return 121;
                        }
                    case "Magus":
                        {
                            return 122;
                        }
                    case "War Kahuna":
                        {
                            return 123;
                        }
                    case "Beast Master":
                        {
                            return 124;
                        }
                    case "Guide":
                        {
                            return 200;
                        }
                    case "Holy Warrior":
                        {
                            return 201;
                        }
                    case "Cleric":
                        {
                            return 202;
                        }
                    case "Breeder":
                        {
                            return 203;
                        }
                    case "Knight":
                        {
                            return 210;
                        }
                    case "Soldier":
                        {
                            return 211;
                        }
                    case "Bishop":
                        {
                            return 212;
                        }
                    case "Priest":
                        {
                            return 213;
                        }
                    case "Soul Breeder":
                        {
                            return 214;
                        }
                    case "Templar":
                        {
                            return 220;
                        }
                    case "Mercenary":
                        {
                            return 221;
                        }
                    case "Cardinal":
                        {
                            return 222;
                        }
                    case "Oracle":
                        {
                            return 223;
                        }
                    case "Master Breeder":
                        {
                            return 224;
                        }
                    case "Stepper":
                        {
                            return 300;
                        }
                    case "Strider":
                        {
                            return 301;
                        }
                    case "Dark Magician":
                        {
                            return 302;
                        }
                    case "Sorcerer":
                        {
                            return 303;
                        }
                    case "Assassin":
                        {
                            return 310;
                        }
                    case "Shadow Hunter":
                        {
                            return 311;
                        }
                    case "Chaos Magician":
                        {
                            return 312;
                        }
                    case "Warlock":
                        {
                            return 313;
                        }
                    case "Battle Summoner":
                        {
                            return 314;
                        }
                    case "Slayer":
                        {
                            return 320;
                        }
                    case "Deadeye":
                        {
                            return 321;
                        }
                    case "Void Mage":
                        {
                            return 322;
                        }
                    case "Corruptor":
                        {
                            return 323;
                        }
                    case "Overlord":
                        {
                            return 324;
                        }
                }
            }
            return 0;
        }

        //Load List based on Tab Selected
        private void load_on_tab(object sender, EventArgs e)
        {
            //Load information about item/state destination
            bool items_to_itembox = Properties.Settings.Default.item_to_itembox;
            bool items_to_clipboard = Properties.Settings.Default.item_to_clipboard;

            //Display information about item/state destination
            if (items_to_itembox == true)
            {
                item_to_warning.Text = "Items are being sent to the Item Box";
                item_to_warning2.Text = "Items are being sent to the Item Box";
            }
            if (items_to_clipboard == true)
            {
                item_to_warning.Text = "Items are being sent to the Clip Board";
                item_to_warning2.Text = "Items are being sent to the Clip Board";
            }
            if (states_to_clipboard == true)
            {
                states_to_warning.Text = "States are being sent to the Clip Board";
            }
            if (states_to_telnet == true)
            {
                states_to_warning.Text = "States are being sent to the Game-Server (Telnet)";
            }
            
            //If Tab Selected = Summon
            if (tabControl1.SelectedIndex == 1)
            {
                //If user has defined auto tamed to be true
                if (auto_tamed == true)
                {
                    tamed.Checked = true;
                }
                else
                {
                    tamed.Checked = false;
                }

                //Set Path for the File to be loaded
                string str = Path.Combine(this.tmp, "summon_list.txt");
                string str1 = str;

                //If the summon_grid hasn't already been populated
                if (summon_grid.Rows.Count == 1)
                {
                    //If the desired list doesn't exist
                    if (!File.Exists(str))
                    {
                        //Using our embedded list
                        using (StreamReader streamReader = summon_list)
                        {
                            //We write a new list to the application directory
                            using (TextWriter streamWriter = new StreamWriter(File.Create(str1)))
                            {
                                streamWriter.Write(streamReader.ReadToEnd());
                            }
                            //Now we should execute the initial load command
                            load_summon();
                        }
                    }
                    else
                    {
                        //We should execute the initial load command
                        load_summon();
                    }
                }
            }
            //If Tab Selected = Item
            if (tabControl1.SelectedIndex == 2)
            {
                //Set Path for the File to be loaded
                string str = Path.Combine(this.tmp, "item_list.txt");
                string str1 = str;

                //If the item grid hasn't already been populated
                if (item_grid.Rows.Count == 1)
                {
                    //If the desired list doesn't exist
                    if (!File.Exists(str))
                    {
                        //Using our embedded list
                        using (StreamReader streamReader = item_list)
                        {
                            //We write a new list to the application directory
                            using (TextWriter streamWriter = new StreamWriter(File.Create(str1)))
                            {
                                streamWriter.Write(streamReader.ReadToEnd());
                            }
                            bgw = new BackgroundWorker();
                            bgw.DoWork += load_item;
                            this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                            bgw.RunWorkerCompleted += item_fin;
                            bgw.RunWorkerAsync();

                        }
                    }
                    else
                    {
                        bgw = new BackgroundWorker();
                        bgw.DoWork += load_item;
                        this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                        bgw.RunWorkerCompleted += item_fin;
                        bgw.RunWorkerAsync();
                    }
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                string str = Path.Combine(this.tmp, "state_list.txt");
                string str1 = str;

                this.Invoke(new MethodInvoker(delegate { state_time_type.SelectedIndex = 0; }));

                if (state_grid.Rows.Count == 1)
                {
                    if (!File.Exists(str))
                    {
                        using (StreamReader streamReader = state_list)
                        {
                            using (TextWriter streamWriter = new StreamWriter(File.Create(str1)))
                            {
                                streamWriter.Write(streamReader.ReadToEnd());
                            }
                            bgw = new BackgroundWorker();
                            bgw.DoWork += load_state;
                            this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                            bgw.RunWorkerCompleted += state_fin;
                            bgw.RunWorkerAsync();

                        }
                    }
                    else
                    {
                        bgw = new BackgroundWorker();
                        bgw.DoWork += load_state;
                        this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                        bgw.RunWorkerCompleted += state_fin;
                        bgw.RunWorkerAsync();
                    }                  
                }
            }
        }

        //On Read Item Finished
        public void item_fin(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Invoke(new MethodInvoker(delegate { item_grid.AllowUserToAddRows = false; }));
            this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\n"+items_read+" Items were loaded from local item_list.txt\n>"); }));
            this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
        }

        //On Read State Finished
        public void state_fin(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Invoke(new MethodInvoker(delegate { state_grid.AllowUserToAddRows = false; }));
            this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\n" + states_read + " States were loaded from local state_list.txt\n>"); }));
            this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
        }

        //Insert Summon
        public void insert_summon()
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                try
                {
                    sqlCon.Open();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                SqlCommand command = new SqlCommand("SELECT TOP (1)sid, name, account, account_id FROM " + Properties.Settings.Default.db_name + ".dbo.Character WHERE name = '" + char_list.SelectedItem + "'", sqlCon);

                try
                {
                    SqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            char_sid = reader.GetInt32(0);
                            char_name = reader.GetString(1);
                            acc_name = reader.GetString(2);
                            acc_id = reader.GetInt32(3);
                        }
                    }
                    sqlCon.Close();
                    sqlCon.Open();
                    SqlCommand insert = new SqlCommand("INSERT INTO "+db_name+".dbo.PaidItem(account_id,avatar_id,avatar_name,item_code,item_count,rest_item_count,bought_time,valid_time,server_name,taken_avatar_id,taken_avatar_name,taken_server_name,taken_time,taken_account_id,confirmed,confirmed_time,isCancel)VALUES(" + acc_id + "," + char_sid + ",'" + char_name + "', " + insert_summon_id + ",1,1,GETDATE(),NULL,NULL,NULL,NULL,NULL,NULL," + acc_id + ",NULL,NULL,0)", sqlCon);
                    this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                    insert.ExecuteNonQuery();
                    this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\nNon-Tamed Summon Delivered to " + char_list.SelectedItem + "'s Item Box\n>"); }));
                    this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
        }

        //Insert Item
        public void insert_item()
        {
            DataGridViewRow row = item_grid.CurrentCell.OwningRow;
            int item_id_ret = Convert.ToInt32(row.Cells["item_id"].Value);
            int item_amt_ret = Convert.ToInt32(row.Cells["item_amount"].Value);
            int item_lv_ret = Convert.ToInt32(row.Cells["item_lv"].Value);
            int item_enc_ret = Convert.ToInt32(row.Cells["item_enc"].Value);

            if (item_amt_ret == 0)
            {
                item_amt_ret = 1;
            }

            string clip_cmd = "/run insert_item(\""+item_id_ret+"\","+item_amt_ret+","+item_lv_ret+","+item_enc_ret+",2,\"" + char_list.SelectedItem + "\")";

            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a player name first!");
            }
            else
            {
                if (Properties.Settings.Default.item_to_itembox == true)
                {
                    if (item_lv_ret != 0 || item_enc_ret != 0)
                    {
                        if (MessageBox.Show("You can not send Leveled/Enchanted items to the Item Box!\n\nWould you like to send to Clip Board instead?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {
                            sendtoclip(clip_cmd);
                        }
                    }
                    else
                    {
                        using (SqlConnection sqlCon = new SqlConnection(connectionString))
                        {
                            try
                            {
                                sqlCon.Open();
                            }
                            catch (SqlException ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                            SqlCommand command = new SqlCommand("SELECT TOP (1)sid, name, account, account_id FROM " + db_name + ".dbo.Character WHERE name = '" + char_list.SelectedItem + "'", sqlCon);

                            try
                            {
                                SqlDataReader reader = command.ExecuteReader();

                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        char_sid = reader.GetInt32(0);
                                        char_name = reader.GetString(1);
                                        acc_name = reader.GetString(2);
                                        acc_id = reader.GetInt32(3);
                                    }
                                }
                                sqlCon.Close();
                                sqlCon.Open();
                                SqlCommand insert = new SqlCommand("INSERT INTO "+db_name+".dbo.PaidItem(account_id,avatar_id,avatar_name,item_code,item_count,rest_item_count,bought_time,valid_time,server_name,taken_avatar_id,taken_avatar_name,taken_server_name,taken_time,taken_account_id,confirmed,confirmed_time,isCancel)VALUES(" + acc_id + "," + char_sid + ",'" + char_name + "', " + item_id_ret + ","+item_amt_ret+","+item_amt_ret+",GETDATE(),NULL,NULL,NULL,NULL,NULL,NULL," + acc_id + ",NULL,NULL,0)", sqlCon);
                                this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                                insert.ExecuteNonQuery();
                                this.Invoke(new MethodInvoker(delegate { richTextBox1.AppendText("\nItem Delivered to " + char_list.SelectedItem + "'s Item Box\n>"); }));
                                this.Invoke(new MethodInvoker(delegate { status.Text = "Idle"; }));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }

                        }
                    }
                }
                if (Properties.Settings.Default.item_to_clipboard == true)
                {
                    sendtoclip(clip_cmd);
                }
            }
        }

        //Insert State
        public void insert_state()
        {
            DataGridViewRow row = state_grid.CurrentCell.OwningRow;
            int state_id = Convert.ToInt32(row.Cells["state_id"].Value);
            int state_lv = Convert.ToInt32(row.Cells["state_lv"].Value);

            if (state_lv == 0)
            {
                state_lv = 1;
            }

            if (states_to_telnet == true)
            {
                if (eventbuff.Checked == true)
                {
                    cmd_txt = "#add_event_state(\""+state_id+"\", \""+state_lv+"\")";
                }
                else
                {
                    if (statein_time.Text != "")
                    {
                        double fin_time_val = 0;

                        if (state_time_type.Text != "")
                        {
                            if (state_time_type.Text == "min")
                            {
                                fin_time_val = TimeSpan.FromMinutes(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            if (state_time_type.Text == "hour")
                            {
                                fin_time_val = TimeSpan.FromHours(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            if (state_time_type.Text == "day")
                            {
                                fin_time_val = TimeSpan.FromDays(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            cmd_txt = "#add_state(\"" + state_id + "\", \"" + state_lv + "\", \"" + fin_time_val + "\", \"" + char_list.SelectedItem + "\"";
                        }
                        else
                        {
                            MessageBox.Show("You must select a Buff Time Type!");
                        }
                    }
                }
                sendcommand(cmd_txt);
            }
            if (states_to_clipboard == true)
            {
                string clip_cmd = "";

                if (eventbuff.Checked == true)
                {
                    clip_cmd = "#add_event_state(\"" + state_id + "\", \"" + state_lv + "\")";
                }
                else
                {
                    if (statein_time.Text != "")
                    {
                        double fin_time_val = 0;

                        if (state_time_type.Text != "")
                        {
                            if (state_time_type.Text == "min")
                            {
                                fin_time_val = TimeSpan.FromMinutes(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            if (state_time_type.Text == "hour")
                            {
                                fin_time_val = TimeSpan.FromHours(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            if (state_time_type.Text == "day")
                            {
                                fin_time_val = TimeSpan.FromDays(Convert.ToInt32(statein_time.Text)).TotalSeconds;
                            }
                            clip_cmd = "#add_state(\"" + state_id + "\", \"" + state_lv + "\", \"" + fin_time_val + "\", \"" + char_list.SelectedItem + "\")";
                        }
                        else
                        {
                            MessageBox.Show("You must select a Buff Time Type!");
                        }
                    }
                }
                sendtoclip(clip_cmd);
            }
        }
    }
}
